import { ElMessage } from 'element-plus'
import toCamelCase from '@/utils/toCamelCase'

var ServerIp = window.location.search //获取服务器的ip
let reconnectionCount = 1 // 重新连接的次数
var printernet = {} //获取关于打印机的数据
var numberPrintneed = 1 //需要打印数量
var numberPrinted = 0 //已经打印的数量
let websocket = null //websocket连接

let specialVar = {
  lsfFileVar: {
    varname: 'rfid',
    varvalue: '123456789012345678901234',
  },
}
// 打印机数据
var jsonPrints = {
  Printer: {
    printerinterface: 'RFID_NET', //打印机的链接方式 当前是网络连接
    printernetip: '10.168.1.198', //打印机的ip
    printerdpi: 300, //打印机的分辨率 203，300，600dpi
    printSpeed: 4, //打印速度 单位英寸每秒，2~8有效
    printDarkness: 12, //打印浓度 打印黑度，0~20有效，值越大打印温度越高
    reverse: false, //是否旋转180度打印，即反向打印
    labelhavegap: true, //有间隙标签请设置为true，连续纸请设置为false
  },
  Operate: 'print',
  lsfFilePath: '', // 在实际项目中，使用在线地址 网络在线使用
  // lsfFilePath: 'E:/print/7.1-7-demo.lsf',//本机测试
  labels: [
    {
      lsfFileVarList: [
        {
          //实例数据
          lsfFileVar: {
            varname: 'boxNo', //需要与lsf模版的字段进行关联
            varvalue: '长城台式机153450',
          },
        },
        {
          lsfFileVar: {
            varname: 'rfid', //需要与lsf模版的字段进行关联
            varvalue: '123456789012345678901234',
          },
        },
      ],
    },
  ],
}

// 初始化WebSocket连接
async function initWebSocket(ip) {
  if (typeof WebSocket === 'undefined') {
    alert('您的浏览器不支持websocket！')
    throw new Error('浏览器不支持WebSocket')
  }
  // 服务的ip
  const wsserver = `ws://10.168.1.191:1808/`

  printernet.ip = ip

  // const wsserver = `ws://${process.env.VUE_APP_WS_SERVER || window.location.hostname}:1808/`
  websocket = new WebSocket(wsserver)

  return new Promise((resolve, reject) => {
    websocket.addEventListener('open', (event) => {
      ElMessage({ message: '连接成功', type: 'success', duration: 1000 })
      resolve(websocket)
    })

    websocket.addEventListener('close', (event) => {
      ElMessage({ message: '关闭连接', type: 'warning' })
      reject(new Error('连接已关闭'))
    })

    websocket.addEventListener('error', (event) => {
      ElMessage({
        message: `连接失败，正在尝试第${reconnectionCount}次重新连接...`,
        type: 'warning',
      })
      // handleReconnect() // 实现重连逻辑
    })
    websocket.addEventListener('message', (receiveMsg) => {
      let receivecontent = receiveMsg.data

      // callback(receiveMsg.data)
      if (receivecontent.indexOf('404') != -1) {
        ElMessage({ message: '请检查打印驱动是否存在' })
      } else if (receivecontent.indexOf('101') != -1) {
        ElMessage({ message: '打印机出错了,请检查打印机连接方式或者IP填写是否正确!' })
      }

      if (receivecontent.indexOf('PrinterStatus_USB:') == 0) {
        //打印机状态，返回格式：PrinterStatus_USB:状态码
        var printerstatus = parseInt(receivecontent.replace('PrinterStatus_USB:', ''))
        if (printerstatus != 0) {
          //0是打印机状态正常
          var statusmsg = ''
          if (printerstatus == 88)
            ElMessage({ message: '打印机已经暂停，请按[暂停]按键，再重新打印!' })
          else if (printerstatus == 82)
            ElMessage({ message: '打印机碳带错误，请重新安装碳带后按[取消]按键，再重新打印!' })
          else if (printerstatus == 83)
            ElMessage({ message: '打印机标签错误，请重新安装标签后按[取消]按键，再重新打印!' })
          else if (printerstatus == 89) ElMessage({ message: '标签纸用完了，请安装新标签！' })
          else if (printerstatus == 90)
            ElMessage({ message: 'RFID标签读写错误，请按[取消]按键，再重新打印!' })
          else if (printerstatus == 91 || printerstatus == 92)
            ElMessage({ message: 'RFID标签校准错误，请按[取消]按键，再重新打印!' })
          else if (printerstatus == -1007)
            ElMessage({
              message: '打印机端口异常，请检查打印机是否正常连接且已开机。',
              type: 'error',
            })
          else if (printerstatus == -101)
            ElMessage({ message: '打印机出错了，请检查打印机连接方式或者IP是否填入正确' })
          else {
            ElMessage({ message: '打印机状态异常，错误代码：' + printerstatus })
          }
        } else {
          printlabel()
        }
      } else if (receivecontent.indexOf('Print finished') != -1) {
        //打印完成，返回格式：打印完成(Print finished).
        numberPrinted++
        ElMessage({ message: ' 标签打印成功。', type: 'success' })
        if (numberPrinted < numberPrintneed) {
          printlabel()
        }
        resolve(true)
      } else {
        ElMessage({ message: receivecontent })
      }
    })
  })
}

// 处理WebSocket消息
// functio(callback) {
//   printstart()
//   return new Promise((resolve, reject) => {
//   })
// }

// 重连逻辑示例
function handleReconnect() {
  setTimeout(() => {
    if (!websocket || websocket.readyState === WebSocket.CLOSED) {
      reconnectionCount++
      initWebSocket().catch(console.error) // 可能需要限制重试次数
    }
  }, 3000) // 例如，5秒后尝试重连
}

// 添加关闭连接的清理函数
function closeWebSocket() {
  if (websocket) {
    websocket.close()
    websocket.removeEventListener('open')
    websocket.removeEventListener('close')
    websocket.removeEventListener('error')
    websocket.removeEventListener('message')
    websocket = null
  }
}
// 开始打印标签∑
function printstart() {
  if (websocket == null) {
    alert('请先连接打印服务')
    return
  }
  // websocket.send(jsonPrints) //查询当前连接的打印机
  // websocket.send('ZM_GetPrinterStatus_USB|500') //发送JSON字符串给打印服务

  // this.numberPrinted = 0
  // this.FormData()
  printlabel()
}
//打印标签，即将JSON字符串发给打印服务处理
function printlabel(data) {
  websocket.send(data) //发送JSON字符串给打印服务
}
// 获取需要打印的数据
function printTableData(data, model, field) {
  // 根据model获取打印模板，并填充数据
  if (model == 0) {
    //0为横向模版
    jsonPrints.lsfFilePath = 'http://10.168.1.30:9999/lsf/demo.lsf'
  } else if (model == 1) {
    //1为竖向模版
    // jsonPrints.lsfFilePath = 'http://10.168.1.191:9999/VerticalTemplate.lsf'
    // jsonPrints.lsfFilePath = 'http://10.168.1.191:7001/7.1-7-demozong.lsf'
  } else if (model == 2) {
    //2为方正模版
    // jsonPrints.lsfFilePath = 'http://10.168.1.191:7001/UpRight.lsf'
    // jsonPrints.lsfFilePath = 'http://10.168.1.191:7001/7.1-7-demozong.lsf'
  }

  let specialVar = {
    lsfFileVar: {
      varname: 'rfid',
      varvalue: '123456789012345678901234',
    },
  }
  let lsfFileVarList = []
  lsfFileVarList.push(specialVar)
  // 根据field数组的长度生成剩余的对象
  for (let i = 0; i < field.length; i++) {
    lsfFileVarList.push({
      lsfFileVar: {
        varname: `tab${i + 1}`,
        // 这里假设每个varvalue都是一个示例值，可以根据需要修改
        varvalue: data[toCamelCase(field[i].fieldName)],
      },
    })
  }
  jsonPrints.Printer.printernetip = printernet.ip
  // lsfFileVarList[1].lsfFileVar.varvalue = data[toCamelCase(field[0].fieldName)]
  lsfFileVarList[0].lsfFileVar.varvalue = data.rfid
  jsonPrints.labels[0].lsfFileVarList = lsfFileVarList

  printlabel(JSON.stringify(jsonPrints))
}

export { initWebSocket, closeWebSocket, printstart, printTableData }
